Posts tagged with tips and tricks

Display text in color - Linux terminal

Ever wanted to print text in colours? You can do it with ANSI escape characters. You can use ANSI codes in any programming language as long as the terminal supports it.

echo -e "\e[31mRed"

Red

echo -e "\e[32mGreen"

Green

Replace the number to get different colors. You can make text bold, italics, underline etc. Following is a short table describing several codes.

39     Default
30     Black     
31     Red   
32     Green   
33     Yellow   
34     Blue   
35     Magenta
36     Cyan   
37     Light gray   
97     White     

For a complete reference, link. (The page has a complete list of ANSI codes)

Automating scripts using expect

Expect is one way to automate your scripts by expecting what the output may be. For example you want to create a script that helps you to login to a telnet session and enter your login and password for you. Here is the simple example which helps you to do it.


Above example will login to your router and enter your username and password and list all the possible commands using ? and then let you to interact with using interact command. You can automate anything for example applications, ssh etc..

How to use variable from bash to use in awk?

If you want to use your variable from script inside awk, do the following

column=2
ps | awk '{print $var}' var=$column


or

name="Hello"
echo $name | awk '{print var}' var=$name

Linux command awk extract anything

Awk is pretty use full when you are writing automatic scripts to do your jobs. Some simple examples of how we can use awk are given below

ps | awk '{print $1}'

It will print first column of ps command.  If you want to print second column also write

ps | awk '{print $1 $2}'

Output seems to be pretty crowded? Add a simple space by

ps | awk '{print $1 " " $2}'

Want to limit it display only second line?

ps | awk ' NR==2{print $1 " " $2}'

Want to exclede first row? You can do it by

ps |awk 'NR !=1{print  $1 " " $2}'

Similarly you can print rows greater than a value by

ps |awk 'NR >1{print  $1 " " $2}'

You can extract virtually anything using awk... Feel free to explore every options. Type man awk or awk --help to explore other options. Feel free to comment also... :)

This site has some good examlpes.


Pass output of one command to argument of other

Well Linux is famous for combining things in power full ways in which anything is possible from a command line. The real fun of Linux came when you start focusing on terminal to do everything...

It's possible to pipeline commands in terminal. Also it's possible to pass output of something as an argument of other.

For example you can ping to your own external ip by

ping $(curl -s  curlmyip.com)

curl curlmyip.com returns you ip address. This address is passed to  the telnet as an argument. Whatever you put between $( and ) will execute as if it is a bash command.